from wtforms import StringField, PasswordField, SelectField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError, Optional

from apps.forms.base_form import BaseForm
from rules.system_user_rule import search_system_user_by_username


class SystemUserForm(BaseForm):
    username = StringField('用户名', validators=[DataRequired(message='请填写用户名')],
                           render_kw={"placeholder": "请填写用户名"})
    real_name = StringField('真实姓名', validators=[DataRequired(message='请填写真实姓名')],
                            render_kw={"placeholder": "请填写真实姓名"})
    password = PasswordField('密码', validators=[DataRequired(message='请填写密码'),
                                                 Length(6, 24, message='须在6～24个字符之间')])
    confirm_password = PasswordField('确认密码', validators=[DataRequired(message='请填写确认密码'),
                                                             Length(6, 24, message='须在6～24个字符之间'),
                                                             EqualTo('password', message='两次密码不一致')])

    role = SelectField('角色', validators=[DataRequired(message='请选择角色')], coerce=str,
                       render_kw={"placeholder": "请选择角色"})

    def __init__(self, *args, **kwargs):
        super(SystemUserForm, self).__init__(*args, **kwargs)
        self.role.choices = self.get_role_list()

    def validate_username(self, field):
        user_orm = search_system_user_by_username(field.data)
        if user_orm:
            raise ValidationError('用户名已被使用')


class UpdateSystemUserForm(BaseForm):
    username = StringField('用户名', validators=[],
                           render_kw={"placeholder": "请填写用户名", "disabled": "disabled"})
    real_name = StringField('真实姓名', validators=[DataRequired(message='请填写真实姓名')],
                            render_kw={"placeholder": "请填写真实姓名"})
    password = PasswordField('密码', validators=[Optional(), Length(6, 24, message='须在6～24个字符之间')])
    confirm_password = PasswordField('确认密码', validators=[Optional(), Length(6, 24, message='须在6～24个字符之间'),
                                                             EqualTo('password', message='两次密码不一致')])

    role = SelectField('角色', validators=[DataRequired(message='请选择角色')], coerce=str,
                       render_kw={"placeholder": "请选择角色"})

    def __init__(self, user_orm=None, *args, **kwargs):
        super(UpdateSystemUserForm, self).__init__(*args, **kwargs)
        self.role.choices = self.get_role_list()

        if user_orm:
            self.username.data = user_orm.username
            self.username.disabled = True
            self.real_name.data = user_orm.real_name
            self.password.data = ""
            self.confirm_password.data = ""
            self.role.data = user_orm.role
